package com.jjb.www.ui.activity;

import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.view.ShapeImageView;
import com.hjq.shape.view.ShapeTextView;
import com.jjb.www.R;
import com.jjb.www.aop.SingleClick;
import com.jjb.www.app.AppActivity;
import com.jjb.www.http.api.EditUserApi;
import com.jjb.www.http.api.RefreshTokenApi;
import com.jjb.www.http.api.UpdateImageApi;
import com.jjb.www.http.api.UserInfoApi;
import com.jjb.www.http.glide.GlideApp;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.dialog.InputDialog;
import com.hjq.http.model.FileContentResolver;
import com.hjq.widget.layout.SettingBar;
import com.jjb.www.ui.dialog.SelectDialog;
import com.jjb.www.utils.CompressionUtil;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * author : Android CRG
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/04/20
 * desc   : 个人资料
 */
public final class PersonalDataActivity extends AppActivity {
    private SettingBar mFlPersonDataAvatar;
    private SettingBar mSetName;
    private SettingBar mSetSex;
    private SettingBar mSetPhone;
    private ShapeImageView mImgHead;
    private ShapeLinearLayout mLlRealName;
    private ShapeImageView mTvSmHead;
    private ShapeTextView mTvSmType;
    private ShapeImageView mImgSmIcon;
    private ShapeTextView mTvSmName;
    private ShapeTextView mTvSmCar;
    private ShapeTextView mTvSmGo;
    private ShapeLinearLayout mLlSmNext;
    //实名状态
    private Integer isAuth = 0;
    private Integer sex = 0;


    /**
     * 头像地址
     */
    private Uri mAvatarUrl;

    @Override
    protected int getLayoutId() {
        return R.layout.personal_data_activity;
    }

    @Override
    protected void initView() {
        mFlPersonDataAvatar = findViewById(R.id.fl_person_data_avatar);
        mImgHead = findViewById(R.id.img_head);
        mSetName = findViewById(R.id.set_name);
        mSetSex = findViewById(R.id.set_sex);
        mSetPhone = findViewById(R.id.set_phone);
        mLlRealName = findViewById(R.id.ll_real_name);
        mTvSmGo = findViewById(R.id.tv_sm_go);

        mTvSmHead = findViewById(R.id.tv_sm_head);
        mTvSmType = findViewById(R.id.tv_sm_type);
        mImgSmIcon = findViewById(R.id.img_sm_icon);
        mTvSmName = findViewById(R.id.tv_sm_name);
        mTvSmCar = findViewById(R.id.tv_sm_car);
        mLlSmNext = findViewById(R.id.ll_sm_next);
        setOnClickListener(mLlSmNext, mFlPersonDataAvatar, mLlRealName, mSetName, mSetSex, mSetPhone);
    }

    @Override
    protected void initData() {
        getUserData();

    }

    private void getUserData() {

        EasyHttp.post(this)
                .api(new RefreshTokenApi()
                        .setUser_id(AppConfig.getInstance().getUserBean().getUser().getId()+""))
                .request(new HttpCallback<HttpData<RefreshTokenApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<RefreshTokenApi.Bean> data) {
                        GlideApp.with(getActivity())
                                .load(data.getData().getUser().getImg())
                                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                .into(mImgHead);
                        sex = data.getData().getUser().getSex();
                        isAuth = data.getData().getUser().getIs_auth();
                        mSetName.setRightText(data.getData().getUser().getNickname());
                        if (data.getData().getUser().getSex() == 1) {
                            mSetSex.setRightText("男");
                        } else {
                            mSetSex.setRightText("女");
                        }

                        String phoneNumber = data.getData().getUser().getMobile();
                        mSetPhone.setRightText(String.format("%s****%s", phoneNumber.substring(0, 3),
                                phoneNumber.substring(phoneNumber.length() - 4)));

                        if (data.getData().getUser().getIs_auth() == 0) {
                            //未实名
                            mTvSmType.setText("未实名认证");
                            mTvSmName.setText("***");
                            mTvSmCar.setText("*********************");
                            mTvSmGo.setText("去实名");
                        } else if (data.getData().getUser().getIs_auth() == 1) {
                            //待审核
                            mTvSmType.setText("实名认证中");
                            mTvSmName.setText(data.getData().getUser().getReal_name());
                            String iCard = data.getData().getUser().getId_card();
                            mTvSmCar.setText(String.format("%s*********%s", iCard.substring(0, 3),
                                    iCard.substring(iCard.length() - 4)));

                            GlideApp.with(getActivity())
                                    .load(R.mipmap.icon_persion_shz)
                                    .into(mImgSmIcon);
                        } else if (data.getData().getUser().getIs_auth() == 2) {
                            //审核成功
                            GlideApp.with(getActivity())
                                    .load(R.mipmap.icon_perison_yrz)
                                    .into(mImgSmIcon);
                            mTvSmType.setText("您已实名认证");
                            mTvSmName.setText(data.getData().getUser().getReal_name());
                            String iCard = data.getData().getUser().getId_card();
                            mTvSmCar.setText(String.format("%s*********%s", iCard.substring(0, 3),
                                    iCard.substring(iCard.length() - 4)));
                        } else {
                            //审核失败
                            GlideApp.with(getActivity())
                                    .load(R.mipmap.icon_persion_wtg)
                                    .into(mImgSmIcon);
                            mTvSmType.setText("未实名认证");
                            mTvSmName.setText("***");
                            mTvSmCar.setText("*********************");
                        }
                    }
                });
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        if (view == mFlPersonDataAvatar) {
            ImageSelectActivity.start(this, data -> {
                // 裁剪头像
                Luban.with(this)
                        .load(new File(data.get(0)))
                        .ignoreBy(100)
                        .setTargetDir(CompressionUtil.getPath(this))
                        .filter(new CompressionPredicate() {
                            @Override
                            public boolean apply(String path) {
                                return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                            }
                        })
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {
                                updateImage(file);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }
                        }).launch();

            });
        } else if (view == mSetName) {
            new InputDialog.Builder(this)
                    // 标题可以不用填写
                    .setTitle(getString(R.string.personal_data_name_hint))
                    .setContent(mSetName.getRightText())
                    //.setHint(getString(R.string.personal_data_name_hint))
                    //.setConfirm("确定")
                    // 设置 null 表示不显示取消按钮
                    //.setCancel("取消")
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setListener((dialog, content) -> {
                        if (!mSetName.getRightText().equals(content)) {
                            mSetName.setRightText(content);
                            editUser("nickname", content);
                        }
                    })
                    .show();
        } else if (view == mSetSex) {
            new SelectDialog.Builder(this)
                    .setTitle("请选择你的性别")
                    .setList("男", "女")
                    // 设置单选模式
                    .setSingleSelect()
                    // 设置默认选中
                    .setSelect(sex == 1 ? 0 : 1)
                    .setListener(new SelectDialog.OnListener<String>() {

                        @Override
                        public void onSelected(BaseDialog dialog, HashMap<Integer, String> data) {

                            for (Object key:data.keySet()) {
                                mSetSex.setRightText(data.get(key));
                                editUser("sex", data.get(key));
                            }

                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                        }
                    })
                    .show();
        } else if (view == mLlRealName) {
            if (isAuth == 2) {
                startActivity(RealNameActivity.class);

            } else if (isAuth == 0) {
                startActivity(GoRealNameActivity.class);
            }

        }
    }

    private void updateImage(File file) {
        EasyHttp.post(PersonalDataActivity.this)
                .api(new UpdateImageApi()
                        .setFile(file))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(PersonalDataActivity.this) {

                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> data) {

                        editUser("avatar_id", data.getData().getAttach_id());
                        mAvatarUrl = Uri.parse(data.getData().getPath());
                        GlideApp.with(getActivity())
                                .load(mAvatarUrl)
                                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                .into(mImgHead);
                    }
                });
    }

    /**
     * 裁剪图片
     */
    private void cropImageFile(File sourceFile) {
        ImageCropActivity.start(this, sourceFile, 1, 1, new ImageCropActivity.OnCropListener() {

            @Override
            public void onSucceed(Uri fileUri, String fileName) {
                File outputFile;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    outputFile = new FileContentResolver(getActivity(), fileUri, fileName);
                } else {
                    try {
                        outputFile = new File(new URI(fileUri.toString()));
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                        outputFile = new File(fileUri.toString());
                    }
                }
//                updateCropImage(outputFile, true);

            }

            @Override
            public void onError(String details) {
                // 没有的话就不裁剪，直接上传原图片
                // 但是这种情况极其少见，可以忽略不计
                updateCropImage(sourceFile, false);
            }
        });
    }

    /**
     * 上传裁剪后的图片
     */
    private void updateCropImage(File file, boolean deleteFile) {
        if (true) {
            if (file instanceof FileContentResolver) {
                mAvatarUrl = ((FileContentResolver) file).getContentUri();
            } else {
                mAvatarUrl = Uri.fromFile(file);
            }
            GlideApp.with(getActivity())
                    .load(mAvatarUrl)
                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                    .into(mImgHead);
        }

        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setFile(file))
                .request(new HttpCallback<HttpData<String>>(this) {

                    @Override
                    public void onSucceed(HttpData<String> data) {
                        editUser("avatar_id", data.getData());

                        mAvatarUrl = Uri.parse(data.getData());
                        GlideApp.with(getActivity())
                                .load(mAvatarUrl)
                                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                .into(mImgHead);
                        if (deleteFile) {
                            file.delete();
                        }
                    }
                });
    }

    private void editUser(String field_name, String value) {
        EasyHttp.put(this)
                .api(new EditUserApi()
                        .setField_name(field_name)
                        .setValue(value))
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {

                        toast("修改成功");
                    }
                });
    }

    ;
}